"""
全球疫情绘图模块
"""
import pyecharts.options as opts
from globaldata import GlobalData
from pyecharts.charts import MapGlobe, Bar, WordCloud
import json


class GlobalChart:
    def __init__(self):
        self.global_data = GlobalData()  # 全球数据
        self.data = {}  # 把文件中的国家和对应的现存确诊人数放在一起，方便排序
        self.percentage_death = {}  # 把死亡率写成百分数
        self.confirmed_count = []  # 各国确诊的总人数

    def bar_base(self) -> Bar:
        """
        各国现存确诊人数柱状图，柱状图方向指向右，参考国内疫情的现存确诊柱状图
        设置zoomdata，参考https://gallery.pyecharts.org/#/Bar/bar_datazoom_inside
        图例去除，标题按百分比居中，为各国现存确诊状况
        鼠标移动到图表上时，会有横竖两条数据轴，参考之前的柱状图设置
        添加底纹，效果参考国内疫情的图表设置
        """
        self.data = dict(
            zip(self.global_data.origin_data['provinceName'], self.global_data.current_confirm_count_of_countries))
        self.data = dict(sorted(self.data.items(), key=lambda dict1: dict1[1], reverse=True))
        x = list(self.data.keys())
        y = list(self.data.values())
        c = (
            Bar()
            .add_xaxis(x[::-1], )
            .add_yaxis("现在确诊", y[::-1], itemstyle_opts=opts.ItemStyleOpts(color="#6999FF"),
                       label_opts=opts.LabelOpts(is_show=False), )
            .reversal_axis()  # 将图形反转
            .set_global_opts(
                tooltip_opts=opts.TooltipOpts(trigger="axis", axis_pointer_type="cross"),
                title_opts=opts.TitleOpts(title="现存确诊主要分布状况", pos_left='30%', pos_top='8%'),
                legend_opts=opts.LegendOpts(
                    type_='plain',
                    is_show=False,
                    orient='horizontal',
                    align='auto'),
                datazoom_opts=[opts.DataZoomOpts(type_="inside", yaxis_index=0, is_zoom_lock=False, range_start=95.5,
                                                 range_end=100), ],
            )  # 可以用鼠标滚轮缩放
            .set_series_opts(
                label_opts=opts.LabelOpts(position="right"),  # 设置为横向的柱状图
            )
            # .render("各国现存确诊人数柱状图.html")
        )
        return c

    def word_cloud_base(self) -> WordCloud:
        """
        各国疫情死亡率词云图，前50，样式大概参考https://gallery.pyecharts.org/#/WordCloud/wordcloud_diamond
        标题按百分比居中
        """
        self.percentage_death = dict(
            zip(self.global_data.origin_data['provinceName'], self.global_data.death_rate_of_countries))
        self.percentage_death = sorted(self.percentage_death.items(), key=lambda dict1: dict1[1], reverse=True)
        words = self.percentage_death[0:50]
        c = (
            WordCloud()
            .add("", words, word_size_range=[12, 60],
                 tooltip_opts=opts.TooltipOpts(trigger="item", formatter="{b}: {c}%"),
                 textstyle_opts=opts.TextStyleOpts(border_color='blue'), shape='diamond')
            .set_global_opts(title_opts=opts.TitleOpts(title="各国疫情死亡率(top 50)", pos_left='33%', pos_top='0%'),
                             tooltip_opts=opts.TooltipOpts(is_show=True))
            # .render("各国疫情死亡率词云图.html")
        )
        return c

    def map_globe_base(self) -> MapGlobe:
        """
        各国累计确诊MapGlobe图，标题按百分比居中
        (看下能不能让鼠标移动到地图上显示出数字，不好弄的话后面再说)
        """
        origin = [['China', 0], ['India', 0], ['United States', 0], ['Indonesia', 0], ['Brazil', 0], ['Pakistan', 0],
                  ['Nigeria', 0], ['Bangladesh', 0], ['Russia', 0], ['Mexico', 0], ['Japan', 0], ['Ethiopia', 0],
                  ['Philippines', 0], ['Egypt', 0], ['Vietnam', 0], ['Dem. Rep. Congo', 0], ['Turkey', 0], ['Iran', 0],
                  ['Germany', 0], ['Thailand', 0], ['United Kingdom', 0], ['France', 0], ['Tanzania', 0], ['Italy', 0],
                  ['South Africa', 0], ['Myanmar', 0], ['Kenya', 0], ['Korea', 0], ['Colombia', 0], ['Spain', 0],
                  ['Uganda', 0], ['Argentina', 0], ['Ukraine', 0], ['Algeria', 0], ['S. Sudan', 0], ['Sudan', 0], ['Iraq', 0],
                  ['Poland', 0], ['Canada', 0], ['Afghanistan', 0], ['Morocco', 0], ['Saudi Arabia', 0], ['Peru', 0],
                  ['Uzbekistan', 0], ['Venezuela', 0], ['Malaysia', 0], ['Angola', 0], ['Mozambique', 0], ['Ghana', 0],
                  ['Nepal', 0], ['Yemen', 0], ['Madagascar', 0], ['North Korea', 0], ["Côte d'Ivoire", 0],
                  ['Cameroon', 0], ['Australia', 0], ['Niger', 0], ['Sri Lanka', 0], ['Burkina Faso', 0],
                  ['Malawi', 0], ['Mali', 0], ['Romania', 0], ['Kazakhstan', 0], ['Syria', 0], ['Chile', 0],
                  ['Zambia', 0], ['Guatemala', 0], ['Zimbabwe', 0], ['Netherlands', 0], ['Ecuador', 0], ['Senegal', 0],
                  ['Cambodia', 0], ['Chad', 0], ['Somalia', 0], ['Guinea', 0], ['South Sudan', 0], ['Rwanda', 0],
                  ['Benin', 0], ['Tunisia', 0], ['Burundi', 0], ['Belgium', 0], ['Cuba', 0], ['Bolivia', 0],
                  ['Haiti', 0], ['Greece', 0], ['Dominican Rep.', 0], ['Czechia', 0], ['Portugal', 0],
                  ['Jordan', 0], ['Sweden', 0], ['Azerbaijan', 0], ['United Arab Emirates', 0], ['Hungary', 0],
                  ['Honduras', 0], ['Belarus', 0], ['Tajikistan', 0], ['Austria', 0], ['Serbia', 0], ['Switzerland', 0],
                  ['Papua New Guinea', 0], ['Israel', 0], ['Togo', 0], ['Sierra Leone', 0], ['Hong Kong', 0],
                  ['Lao PDR', 0], ['Bulgaria', 0], ['Paraguay', 0], ['Libya', 0], ['El Salvador', 0], ['Nicaragua', 0],
                  ['Kyrgyzstan', 0], ['Lebanon', 0], ['Turkmenistan', 0], ['Singapore', 0], ['Denmark', 0],
                  ['Finland', 0], ['Congo', 0], ['Slovakia', 0], ['Norway', 0], ['Eritrea', 0],
                  ['State of Palestine', 0], ['Oman', 0], ['Costa Rica', 0], ['Liberia', 0], ['Ireland', 0],
                  ['Central African Rep.', 0], ['New Zealand', 0], ['Mauritania', 0], ['Kuwait', 0], ['Panama', 0],
                  ['Croatia', 0], ['Moldova', 0], ['Georgia', 0], ['Puerto Rico', 0], ['Bosnia and Herzegovina', 0],
                  ['Uruguay', 0], ['Mongolia', 0], ['Albania', 0], ['Armenia', 0], ['Jamaica', 0], ['Lithuania', 0],
                  ['Qatar', 0], ['Namibia', 0], ['Botswana', 0], ['Lesotho', 0], ['Gambia', 0], ['Gabon', 0],
                  ['North Macedonia', 0], ['Slovenia', 0], ['Guinea-Bissau', 0], ['Latvia', 0], ['Bahrain', 0],
                  ['Swaziland', 0], ['Trinidad and Tobago', 0], ['Eq. Guinea', 0], ['Timor-Leste', 0],
                  ['Estonia', 0], ['Mauritius', 0], ['Cyprus', 0], ['Djibouti', 0], ['Fiji', 0], ['Réunion', 0],
                  ['Comoros', 0], ['Bhutan', 0], ['Guyana', 0], ['Macao', 0], ['Solomon Islands', 0], ['Montenegro', 0],
                  ['Luxembourg', 0], ['Western Sahara', 0], ['Suriname', 0], ['Cabo Verde', 0], ['Micronesia', 0],
                  ['Maldives', 0], ['Guadeloupe', 0], ['Brunei', 0], ['Malta', 0], ['Bahamas', 0], ['Belize', 0],
                  ['Martinique', 0], ['Iceland', 0], ['French Guiana', 0], ['French Polynesia', 0], ['Vanuatu', 0],
                  ['Barbados', 0], ['New Caledonia', 0], ['Mayotte', 0], ['Sao Tome & Principe', 0], ['Samoa', 0],
                  ['Saint Lucia', 0], ['Guam', 0], ['Channel Islands', 0], ['Curaçao', 0], ['Kiribati', 0],
                  ['St. Vincent & Grenadines', 0], ['Tonga', 0], ['Grenada', 0], ['Aruba', 0],
                  ['U.S. Virgin Islands', 0], ['Antigua and Barbuda', 0], ['Seychelles', 0], ['Isle of Man', 0],
                  ['Andorra', 0], ['Dominica', 0], ['Cayman Islands', 0], ['Bermuda', 0], ['Greenland', 0],
                  ['Saint Kitts & Nevis', 0], ['American Samoa', 0], ['Northern Mariana Islands', 0],
                  ['Marshall Islands', 0], ['Faeroe Islands', 0], ['Sint Maarten', 0], ['Monaco', 0],
                  ['Liechtenstein', 0], ['Turks and Caicos', 0], ['Gibraltar', 0], ['San Marino', 0],
                  ['British Virgin Islands', 0], ['Caribbean Netherlands', 0], ['Palau', 0], ['Cook Islands', 0],
                  ['Anguilla', 0], ['Wallis & Futuna', 0], ['Tuvalu', 0], ['Nauru', 0], ['Saint Pierre & Miquelon', 0],
                  ['Montserrat', 0], ['Saint Helena', 0], ['Falkland Is.', 0], ['Niue', 0], ['Tokelau', 0],
                  ['Holy See', 0]]
        origin = dict(origin)  # 转换成字典，便于下面的处理
        self.fix_name()  # 名称修正
        self.confirmed_count = list(
            zip(self.global_data.names_of_countries, self.global_data.confirmed_count_of_countries))
        for i in range(0, len(self.confirmed_count)):
            if self.confirmed_count[i][0] in origin:
                origin[self.confirmed_count[i][0]] = self.confirmed_count[i][1]
        origin = [list(i) for i in origin.items()]  # 转换成嵌套列表
        low, high = min(self.global_data.confirmed_count_of_countries), max(
            self.global_data.confirmed_count_of_countries)
        c = (
            MapGlobe()
            .add_schema()
            .add(
                maptype="world",
                series_name="各国确诊人数",
                data_pair=origin,
                is_map_symbol_show=False,
                label_opts=opts.LabelOpts(is_show=False),
                tooltip_opts=opts.TooltipOpts(trigger="item", formatter="{c}"),
            )
            .set_global_opts(
                # title_opts=opts.TitleOpts(title="各国累计确诊人数", pos_bottom='50%'),  # 这样写只能在画出的图里显示标题
                tooltip_opts=opts.TooltipOpts(trigger="item", formatter="{c}"),
                visualmap_opts=opts.VisualMapOpts(
                    dimension=0,
                    is_show=False,
                    pos_top='10%',
                    pos_left='30%',
                    min_=low,
                    max_=high,
                    type_='color',
                    range_text=["max", "min"],
                    range_size=[0, 1],
                    is_calculable=True,
                    range_color=["silver", "#800000"],
                )
            )
            # .render("各国确诊人数图.html")
        )
        return c

    def fix_name(self):
        with open("data/fixed_name.json") as file:
            fix_dict = json.load(file)
        lengthy = len(self.global_data.names_of_countries)
        for i in range(0, lengthy):
            key = self.global_data.names_of_countries[i]
            if key in fix_dict:
                self.global_data.names_of_countries[i] = fix_dict[key]


if __name__ == "__main__":
    py = GlobalChart()
    py.bar_base()
    py.word_cloud_base()
    py.map_globe_base()
